import {
  findAddress,
  getAddressList
} from '/api/address';
var app = new getApp();
const userRentalAgreement = 'https://img.ddzuji.cn/agreements/userRentalAgreement/title'
Page({
  data: {
    imgUrl: "", //图片路径
    ossImg: `${app.globalData.imgUrl}/applet_web_images/new_image`,
    phone: '',
    goods_id: '',
    phone_secret: "", //隐藏后的手机号
    cho: "0", //是否同意协议，0不同意，1同意
    show: "0", //勾选tip的显示
    depositState: "", //-1不免，0半免，1全免
    orderDetail: [], //订单详情
    eme_contact: "", // 紧急联系人
    eme_contact_phone: "", // 紧急联系人电话
    eme_contact_relation: 1, // 紧急联系人关系
    relationList: [{
        label: "父母",
        value: 1
      },
      {
        label: "配偶",
        value: 2
      },
      {
        label: "亲属",
        value: 3
      },
      {
        label: "同事",
        value: 4
      },
    ],
    goodsDetail: [], //返回的商品信息
    voucherList: [], //优惠券列表
    selectvoucherid: 0, //当前选择的优惠券id
    usingVoucher: {}, //要使用的优惠券
    clickNotUse: false, //点击“不使用优惠券”
    orderNo: "", //芝麻订单号
    outOrderNo: "", //商户订单号
    order_id: "", //订单号
    shadowAnimation: [], //动画-背景
    contentAnimation: [], //动画-面板
    layerAnimation: [], //动画-弹出层
    voucherHidden: true, //优惠券面板
    freePaymentHidden: true, //免密支付弹出层
    authorizedHidden: true, //支付宝资金授权弹出层
    actual_payment_Details: true, // 实付详情弹出层
    submitFlag: true, //避免重复提交  
    isLoad: false,
    // emailstr: "",
    isxuzu: false,
    emailSuffixs: ["@qq.com", "@163.com", "@gmail.com", "@msn.com", "@163.net", "@yahoo.com", "@hotmail.com", "@ask.com", "@live.com", "@mail.com"],
    showEngine: false,
    remark: "", //备注信息
    is_financial: 0, //是否显示协议  征信
    is_warrant: 0, //是否显示协议 担保
    tap_role_index: -1, //点击的使用规则说明
    down_payment: "0.00", //首期应付金额
    down_payments: "0.00", //一元首期应付金额
    is_showTips: true, //顶部警告
    address_info: null, //地址信息
    buyOutMsg: {}, //买断信息
    isUploadUserInfo: false,
    isHoriShow: false, // 下单确认弹窗
    orderParams: {},
    cou_list: [],
    current: '',
    coupon_price: '请选择',
    user_voucher_id: '', //选中的优惠劵ID
    active_id: '', //
    attr_id: '',
    exclusive_price: '', // 专享价
    is_skip_face_auth: null,
    sesame_exclusive_discount_amount: '', // 专享优惠
    is_show_exclusive: false, // 是否展示专享价
    is_exclusive_discounts: false, // 是否展示专享优惠
    switch: 'switch_opened',
    locationHide: false, // 地址弹窗
    locationErrorCode: '', // 地址错误码
    showKefuPop: false, // 客服弹窗
    couponMaxPrice: '', // 优惠券最大值
    couponStrength: '', //优惠券力度
    couponTime: '', // 优惠券时间 
    submitParam: {}, // 提交订单所需数据
    _orderStr: '', // 支付宝支付必备参数
    contractHide: false, // 合同弹窗
    currentContractIndex: '0', // 当前合同弹窗ID
    contractArray: [
      `${userRentalAgreement}-1-01.jpg?id=1`,
      `${userRentalAgreement}-1-02.jpg?id=2`,
      `${userRentalAgreement}-1-03.jpg?id=3`,
      `${userRentalAgreement}-1-04.jpg?id=4`,
      `${userRentalAgreement}-1-05.jpg?id=5`,
      `${userRentalAgreement}-1-06.jpg?id=6`,
      `${userRentalAgreement}-1-07.jpg?id=7`,
      `${userRentalAgreement}-1-08.jpg?id=8`,
      `${userRentalAgreement}-1-09.jpg?id=9`,
      `${userRentalAgreement}-1-10.jpg?id=10`,
      `${userRentalAgreement}-1-11.jpg?id=11`,
      `${userRentalAgreement}-1-12.jpg?id=12`,
      `${userRentalAgreement}-1-13.jpg?id=13`,
    ],
    eSignAuthAgreement: 'https://img.ddzuji.cn/agreements/eSignAuthAgreement/eSignAuthAgreement.jpg?id=1',
    isSelectBrokenScreen: true, // 是否默认勾选switch碎屏险
    safePopupVisible: false,  // 碎屏挽留弹窗
    safe_id: 0, // 碎屏险ID
    isHideBrokenScreen: false, // 是否选中展示碎屏服务
    safe_price: '', // 碎屏险价格
    temporarilyBrokenScreen: false, // 暂时碎屏险控制
    couponMaxPriceId: 0, // 优惠券ID
    delivery_latitude: '', // 风控信息
    delivery_longitude: '', // 风控信息
    delivery_add_code: '', // 风控信息
    zm_user_id: '', // 外链跳转用户ID
    link_source: '', // 是否服务消息调过来的
    isHideOriginFirstInstallmentRent: true, // 是否隐藏原首期实付金额
    isHideRemainingTotalRent: true, // 是否隐藏剩余总租金
    buyoutPriceVisible: false, // 买断价弹窗
    isShowBuyoutPrice: false, // 是否显示买断价
    buyoutList: [] // 买断价列表
  },

  // 继续选择碎屏保障
  selectProtection() {
    this.setData({
      safePopupVisible: false,
      isSelectBrokenScreen: true,
      temporarilyBrokenScreen: true
    })
    this.getOrderDetail()
  },
  // 不选购
  notSelectProtection() {
    this.setData({
      safePopupVisible: false,
      temporarilyBrokenScreen: false
    })

    this.getOrderDetail()
  },

  // h5页面回调函数
  jumpNoSesameRentMachine() {
    my.navigateTo({
      url: '/page/rent/h5/noSesameRentMachine/noSesameRentMachine'
    })
  },
  // 封装拒量用户函数
  refusalQuantityUser() {
    let { testUrl, user_id } = app.globalData
    my.request({
      url:  `${testUrl}/api/user/getUserType`,
      method: 'POST',
      data: {
        zm_user_id: user_id
      },
      success: (res) => {
        let { user_type } = res.data.data
        
        if(user_type) {
          // 提交PV、UV接口
          my.request({
            url:  `${testUrl}/api/index/activityRecord`,
            data: {
              source: 5,
              user_id
            },
            success: () => {
              my.request({
                url: `${testUrl}/api/help/getProjectConfig?key=user_tag_status`,
                method: 'get',
                success: (res) => {
                  const { data: { data } } = res
                  if(!data || data === '0') {
                    return
                  }
                  my.request({
                    url: `${testUrl}/api/index/getRefuseDiversionPageNum`,
                    method: 'get',
                    success: (res) => {
                      const jumpPage = {
                        0: '',
                        1: '/page/rent/h5/noSesameRentMachine/noSesameRentMachine',
                        2: '/page/rent/h5/noSesameRentMachine/refusalQuantity1/refusalQuantity1',
                        3: '/page/rent/h5/noSesameRentMachine/refusalQuantity2/refusalQuantity2',
                        4: '/page/rent/h5/noSesameRentMachine/refusalQuantity3/refusalQuantity3',
                        5: '/page/rent/h5/noSesameRentMachine/refusalQuantity4/refusalQuantity4',
                        6: '/page/rent/h5/noSesameRentMachine/refusalQuantity5/refusalQuantity5',
                        7: '/page/rent/h5/noSesameRentMachine/refusalQuantity6/refusalQuantity6',
                        8: '/page/rent/h5/noSesameRentMachine/refusalQuantity7/refusalQuantity7',
                      }
                      const { data: key, code, msg } = res.data
                      if(code !== 1) {
                        my.showToast({
                          type:'fail',
                          content: msg
                        })
                        return
                      }
                      if(jumpPage[key]) {
                        my.navigateTo({
                          url: jumpPage[key]
                        })
                      }
                    }
                  })
                  my.hideLoading()
                }
              })
            }
          })
        }
      }
    })
    
  },

  // 选择碎屏险
  selectBrokenScreen() {
    
    const { isSelectBrokenScreen  } = this.data
    this.setData({
      isSelectBrokenScreen: !isSelectBrokenScreen
    })
    
    if(!this.data.isSelectBrokenScreen) {
      this.setData({
        safePopupVisible: true,
      })
    } else {
      this.setData({
        temporarilyBrokenScreen: true
      })
      this.getOrderDetail()
    }
  },

// 已成功阅读
  successfullyRead() {
    this.setData({
      contractHide: false,
      cho: '1'
    })
  },
  // 关闭合同弹窗
  closeContract() {
    this.setData({
      contractHide: false
    })
  },

  openBuyoutPrice() {
    this.setData({
      buyoutPriceVisible: true
    })

    const { testUrl } = getApp().globalData
    const {
      goods_label,
      goods_official_price,
      is_first_month_one_yuan: is_credit,
      order_tenancy_term: term,
      order_actual_month_rent: goods_month_rent
     } = this.data.orderDetail
    my.request({
      url: `${testUrl}/api/goods/getGoodsGradientBuyoutPriceInfo`,
      method: 'POST',
      data: {
        is_credit,
        term,
        goods_actual_month_rent: goods_month_rent,
        goods_official_price,
        goods_label
      },
      success: (res) => {
        const { code, msg, data } = res.data
        if(code !== 1) {
          my.showToast({
            type: 'none',
            content: msg,
            duration: 3000
          });
          return
        }
        this.setData({
          buyoutList: data
        })
      },

    });
  },

  closeBuyoutPrice() {
    this.setData({
      buyoutPriceVisible: false
    })
  },

  previeweSignAuth() {
    const { eSignAuthAgreement } = this.data
    my.previewImage({
      urls: [eSignAuthAgreement],
    });
  },
  previewImage(e) {
    console.log(e.target.dataset.index, 'index');
    my.previewImage({
      current: e.target.dataset.index,
      urls: this.data.contractArray,
    });
  },

  // 合同点击
  contractTabClick(e) {
    const { index } = e.target.dataset
    console.log( index);
    this.setData({
      currentContractIndex: index
    })
  },

  // 打开客服弹窗
  showKefu() {
    this.setData({
      showKefuPop: true,
    })
  },

  // 关闭客服弹窗
  hideKefu() {
    this.setData({
      showKefuPop: false,
    })
  },
  // 优惠劵确定按钮
  hidePanels() {
    let vm = this

    this.setData({
      active_id: vm.data.user_voucher_id
    })
    if(!this.user_voucher_id) {
      this.getOrderDetail()
    }
    this.hideShadow();
    this.hideContent();
    this.compute_price()
    setTimeout(() => {
      this.setData({
        voucherHidden: true,
      });
    }, 150);
  },
  //切换优惠卷选中状态
  getCurrent(e) {

    let that = this
    // console.log(e.target.dataset);
    // 如果是点击已经选中的话就取消选中
    if (e.target.dataset.index === that.data.current) {
      this.setData({
        current: that.data.cou_list.length + 1,
        user_voucher_id: ''
      })
    } else {
      // console.log('进来了2', e.target.dataset.index, that.data.current);
      this.setData({
        current: e.target.dataset.index,
        user_voucher_id: e.target.dataset.activeId
      })
    }
  },
  handleOk(e) {
    this.setData({
      eme_contact_relation: e
    })
  },
  // 修改状态
  getIshow(e) {
    console.log(e, 'eeeee');
    let index = e.target.dataset.index
    let isShow = this.data.cou_list[index].isShow
    let _isShow = "cou_list[" + index + "].isShow"
    this.setData({
      [_isShow]: !isShow
    })
  },
  // 获取我的优惠卷列表
  requestVoucherLists() {
    let vm = this
    let app = getApp()
    my.showLoading({
      content: '加载中'
    })
    vm.setData({
      cou_list: []
    })
    const { zm_user_id } = vm.data
    my.request({
      url: app.globalData.testUrl + '/api/voucher/getUserAbleUseVoucherList',
      method: 'POST',
      data: {
        zm_user_id: app.globalData.user_id || zm_user_id,
        goods_id: vm.data.orderDetail.goods_id || '',
        attr_id: Number(vm.data.attr_id)
        // goods_id: 100215,
      },
      dataType: 'json',
      success: function (res) {
        
        vm.setData({
          cou_list: res.data.data
        })
  
        const { cou_list } = vm.data
        
        if(!cou_list.length) { // 没有优惠券
          return
        }
        const { 
          amount:couponMaxPrice,
          voucher_title: couponStrength,
          valid_begin_time,
          valid_end_time,
        } = cou_list[0]
        vm.setData({
          couponMaxPrice,
          couponStrength,
          couponTime: `${valid_begin_time}-${valid_end_time}`
        })
        my.hideLoading()
      }
    })
  },
  //显示弹出层背景
  showShadow() {
    var animation = my.createAnimation({
      duration: 150,
      timingFunction: 'cubic-bezier(.55, 0, .55, .2)',
    });

    this.shadowAnim = animation;

    animation.opacity(1).step();
    this.setData({
      shadowAnimation: animation.export(),
    });
  },
  del_topWarning() {

    this.setData({
      is_showTips: false
    })
  },
  // 隐藏弹出层背景
  hideShadow() {
    this.shadowAnim.opacity(0).step();
    this.setData({
      shadowAnimation: this.shadowAnim.export(),
    });
  },
  // 显示面板
  showContent() {
    var animation = my.createAnimation({
      duration: 150,
      timingFunction: 'cubic-bezier(.55, 0, .55, .2)',
    });
    this.contentAnim = animation;
    animation.translateY(0).step();
    this.setData({
      contentAnimation: animation.export(),
    });
  },
  // 隐藏面板
  hideContent() {
    this.contentAnim.translateY('100%').step();
    this.setData({
      contentAnimation: this.contentAnim.export(),
    });
  },
  // 显示弹出层
  showLayer() {
    var animation = my.createAnimation({
      duration: 150,
      timingFunction: 'cubic-bezier(.55, 0, .55, .2)',
    });
    this.layerAnim = animation;
    animation.opacity(1).scale(1).step();
    this.setData({
      layerAnimation: animation.export(),
    });
  },
  // 隐藏弹出层
  hideLayer() {
    this.layerAnim.scale(.8).opacity(0).step();
    this.setData({
      layerAnimation: this.layerAnim.export(),
    });
  },
  ///////////////////////////////////////////
  //打开面板/弹出层
  showPanel(e) {
    if (e.currentTarget.dataset.origin == "freePayment") {
      this.setData({
        freePaymentHidden: !this.data.freePaymentHidden,
      });

      this.showShadow();
      this.showLayer();

    } else if (e.currentTarget.dataset.origin == "authorized") {
      this.setData({
        authorizedHidden: !this.data.authorizedHidden,
      });

      this.showShadow();
      this.showLayer();
    } else if (e.currentTarget.dataset.origin == "actual_payment_Details") {
      this.setData({
        actual_payment_Details: !this.data.actual_payment_Details,
      });
      this.showShadow();
      this.showContent();
    }
  },

  //打开优惠券面板
  showVoucherPanel() {
    const { active_id, cou_list, user_voucher_id } = this.data

    // 点击需要判断是否选中和选中哪一个
    if (active_id !== '') {
      let indexs = 0
      cou_list.forEach((item, index) => {
        if (item.user_voucher_id === active_id) {
          indexs = index
        }
      })
      this.setData({
        current: indexs,
      });
    } else if(user_voucher_id) {
      const current = cou_list.findIndex(item => item.user_voucher_id === user_voucher_id)
      this.setData({
        current
      })
    } else {
      this.setData({
        current: '',
      });
    }
    this.setData({
      voucherHidden: !this.data.voucherHidden,
    });
    this.showShadow();
    this.showContent();
  },

  //关闭面板/弹出层
  hidePanel(e) {
    this.hideShadow();

    if (e.currentTarget.dataset.style == "panel") {

      this.hideContent();

      setTimeout(() => {
        this.setData({
          voucherHidden: true,
        });
      }, 150);
    } else if (e.currentTarget.dataset.style == "layer") {
      this.hideLayer();

      this.setData({
        freePaymentHidden: true,
        authorizedHidden: true,
      });
    } else if(e.currentTarget.dataset.style === 'actual_payment') {
      this.hideContent()
      this.setData({
        actual_payment_Details: true
      })
    }
  },
  hideEngine() {
    this.setData({
      showEngine: false
    })
  },
  
  onGetAuthorize() {
    let app = getApp();
    app.getUserPhone((res) => {
      this.toReal()
    })
  },

  onAuthError(e) {
    let vm = this
    my.alert({
      title: '提示',
      content: '取消授权，可能会使部分服务无法使用，或者页面信息不完整',
      cancelButtonText: '我知道了',
      success: (result) => {
        // if(result.confirm){
        //   this.onGetAuthorize()
        // }
      }
    });
  },
  toReal() { //跳转实名认证页面(第一次下单用户)
    const { goods_id, is_skip_face_auth } = this.data.orderDetail
    my.navigateTo({
      url: `/page/rent/confirm-order/real/real?goods_id=${goods_id}&is_skip_face_auth=${is_skip_face_auth}`
    })
 
  },
  getAddress() { //获取支付宝收货地址
    // if (my.canIUse('getAddress')) {
    //   let vm = this;
    //   my.getAddress({
    //     success: (res) => {
    //       console.log('success', res);
    //       res.result.address = res.result.prov + res.result.city + res.result.area + res.result.address;

    //       vm.setData({
    //         address_info: res.result

    //       })
    //     },
    //     fail: err => {
    //       my.navigateTo({ url: '/page/mine/addressList/addressList' });
    //     }
    //   });
    // } else {
    //   my.alert({
    //     title: '提示',
    //     content: '当前支付宝版本过低，无法使用此功能，请升级最新版本支付宝'
    //   });
    // }
    my.navigateTo({
      url: '/page/mine/addressList/addressList'
    });
  },

  //选择优惠券
  chooseVoucher(e) {
    var _cou_id = e.currentTarget.dataset.id;

    if (_cou_id == this.data.selectvoucherid) {
      this.setData({
        usingVoucher: {},
        selectvoucherid: 0
      });
      this.compute_price(); //计算金额
      return;
    }

    var usingVoucher = {};

    this.data.voucherList.forEach((arr) => {
      if (arr.id == _cou_id) {
        usingVoucher = arr;
      }
    })
    this.setData({
      voucherList: this.data.voucherList,
      usingVoucher: usingVoucher,
      selectvoucherid: _cou_id
    });

    this.compute_price(); //计算金额
  },

  // 同意协议
  choose() {
    if (this.data.cho == "0") {
      this.setData({
        cho: "1",
        show: "0"
      })
    } else {
      this.setData({
        cho: "0"
      })
    }
  },

  // 查看协议
  toRule(e) {
    this.setData({
      contractHide: true
    })

    // let app = getApp();
    // if (my.canIUse('web-view')) {
    //   my.downloadFile({
    //     url: app.globalData.imgUrl + "yonghuzulinxieyi.pdf",
    //     success({
    //       apFilePath
    //     }) {
    //       my.hideLoading();
    //       my.openDocument({
    //         filePath: apFilePath,
    //         fileType: 'pdf',
    //       })
    //     }
    //   })
    // } else {
    //   this.setData({
    //     canUse: false
    //   })
    // }
  },
  // setEmail(e) {//邮箱输入
  //   let _value = e.detail.value;

  //   if (_value.length > 5) {
  //     this.setData({
  //       showEngine: true
  //     })
  //   }

  //   this.setData({
  //     emailstr: e.detail.value
  //   })
  // },
  setEmeContact(e) {
    this.setData({
      eme_contact: e.detail.value
    })
  },
  setEmeContactPhone(e) {
    this.setData({
      eme_contact_phone: e.detail.value
    })
  },
  handleButtonTap(e) {
    e === 1 ? this.gotoUserInfo() : this.submit_order(this.data.orderParams)
  },
  // 提交订单
  async subOrder() {
    
    var obj = this;
    if (this.data.orderDetail.goods_id !== 100194) {
      if (!obj.data.address_info) {
        my.showToast({
          type: 'none',
          content: '请选择收货信息~',
          duration: 500  
        });
        return
      }

     // 租赁方式不能为空
    if(!this.data.orderDetail.rental) {
        my.alert({
          content: '租赁方式不能为空,请联系客服',
          buttonText: '联系客服',
          success: () => {
            this.showKefu()
          }
        });
        return;
      }

       const {
        mobilePhone,
        fullname,
        address: addressValue,
        provinces,
        city,
        district
       } = obj.data.address_info


      //  有的旧数据省市区是为undefined或空字符串，后期稳定用include数组方法过滤
       if(!mobilePhone || !fullname || !addressValue || !provinces || !city || !district) {
          my.alert({
            title: '',
            content: '您的地址信息不全，请更新后再次选择收货地址',
            buttonText: '去更新',
            success: () => {
              my.navigateTo({
                url: '/page/mine/addressList/addressList'
              })
            }
          });
          return
       }

      if (this.data.is_auth != 1) {
        my.showToast({
          type: 'none',
          content: '请先进行实名认证哦~',
          duration: 500,
          success: () => {

          }
        });
        return;
      }

    }

    if (this.data.cho == "0") {
      if (this.data.show == "0") {
        this.setData({
          show: "1"
        })
      } else {
        this.setData({
          show: "0"
        })
      }
    } else {
      //console.log("asdfsdf",e)
      const {
        provinces,
        city,
        district
       } = obj.data.address_info
 
      let submitParam = {
        order_id: obj.data.orderDetail.order_id, //订单id
        link_source: obj.data.link_source,
        user_phone: app.globalData.userPhone, //支付宝绑定手机号
        receiver_phone: obj.data.address_info.mobilePhone, //收货手机号
        receiver_name: obj.data.address_info.fullname, //收货人姓名
        user_address: obj.data.address_info.address, //用户地址
        area: obj.data.address_info.area,
        cou_id: obj.data.selectvoucherid, //使用优惠券id
        // form_id: e.detail.formId, //formId,//推送模板消息form_id
        remarks: obj.data.remark, //备注信息
        user_email: "88888666@qq.com", //邮箱
        zm_user_id: app.globalData.user_id, //用户id
        eme_contact: obj.data.eme_contact,
        eme_contact_phone: obj.data.eme_contact_phone,
        eme_type: obj.data.eme_contact_relation,
        exclusive_price: obj.data.exclusive_price,
        provinces,
        city,
        district,
        applet_version: '1.0'
      }

      this.setData({
        submitParam
      })

      // if (obj.data.orderDetail.get_position == 1) { //是否已经授权定位信息 值为1代表该用户已授权获取位置信息，值为0 未授权
      //   if (my.canIUse("getLocation")) {
      //     submitParam.position_info = await obj.getLocation();
      //   }
      // } else {
      //   app.globalData.get_position = 0;
      // }

      if (obj.data.submitFlag) {
        obj.submit_order(submitParam);
      }
    }
  },

  async getLocation() { //获取定位信息
    return new Promise(resolve => {
      const {
        user_id: zm_user_id,
        testUrl
      } = getApp().globalData
      const {
        order_id
      } = this.data.orderDetail
      my.getLocation({
        type: 2,
        success: (res) => {
          const { 
            latitude: delivery_latitude,
            longitude: delivery_longitude,
            cityAdcode: delivery_add_code
          } = res
          this.setData({
            delivery_latitude,
            delivery_longitude,
            delivery_add_code
          })
          my.request({
            url: `${testUrl}/Api/user/canGetPosition`,
            method: 'POST',
            data: {
              ...res,
              zm_user_id,
              order_id
            },
            dataType: 'json',
            success: ({data}) => {
              let { status } = data
              if(status !== '1001') {
                my.showToast({
                  type: 'none',
                  content: '地址获取异常，请重新尝试'
                })
                return
              }
    
              resolve(data)
            },
            fail() {
              my.showToast({
                type: 'none',
                content: '网络连接异常，请稍后再获取地址'
              })
            },
            complete: () => {
              my.hideLoading(); //加载结束
            }
          });
        },
        fail: ({error}) => {
          resolve(error);
          this.setData({
            locationErrorCode: error
          })
          my.hideLoading();
        },
      })
    });

  },

  // 关闭地址授权弹窗
  closeLocation() {
    this.setData({
      locationHide: false
    })

    my.showToast({
      type: 'none',
      content: ' 请先允许"获取位置信息"功能后再下单'
    })
  },

  // 唤起位置界面
  async getLocationPopup() {
    const { locationErrorCode: result } = this.data
    if(result === 2002 || result === 2003) {
        // 打开设置地址界面
        my.openSetting({
          withSubscriptions: true
        })
    } else {
      // 继续下单
      this.subOrder()
    }
    // 关闭弹窗
    this.setData({
      locationHide: false
    })
  },

  async submit_order(submitParam) { //确认提交订单
    //加载动画
    my.showLoading({
      content: '加载中...',
      delay: 0,
    });

    const result = await this.getLocation()
    // 如果结果不是后端返回的对象数据，而是支付宝返回的错误码
    if(Object.prototype.toString.call(result) !== '[object Object]') {
      this.setData({
        locationHide: true
      })
      my.hideLoading()
      return
    }
    
    const {
      delivery_latitude,
      delivery_longitude,
      delivery_add_code
    } = this.data
    submitParam.delivery_latitude = delivery_latitude
    submitParam.delivery_longitude = delivery_longitude
    submitParam.delivery_add_code = delivery_add_code

    // 交易组件(判断当前版本是否可以用checkBeforeAddOrder)
    const paymentOrder = (submitParam) => {
      my.request({
        url: app.globalData.testUrl + '/Api/order/OrderFreeze',
        method: 'POST',
        data: submitParam,
        dataType: 'json',
        success:  (res) => {

          let _orderStr = res.data.data.orderStr

          if (res.data.status == '1001') {
            this.setData({
              _orderStr,
              submitFlag: false // 接口请求成功禁用按钮
            })
            // 人脸识别，拉起预授权
            let { is_skip_face_auth } = this.data
            
            console.log(is_skip_face_auth, 'is_skip_face_auth');
            if(is_skip_face_auth === 1) { // 如果已经人脸识别过
              my.request({
                url: `${app.globalData.testUrl}/api/user/userFaceAuthSuccess`,
                method: 'POST',
                data: {
                  order_id: submitParam.order_id
                },
                dataType: 'json',
                success: () => {
                  this.preAuthorization()
                },
                fail: () => { // 成功和失败都拉起预授权
                  // 拉起预授权
                  this.preAuthorization()
                }
              })
            } else {
              this.authentication()
            }

          } else if (res.data.status == '1002') { // 重复点击下单
            my.showToast({
              type: 'fail',
              content: '系统繁忙',
              duration: 2000
            });
        
          } else if(res.data.status === '1003') { // 风控地址没过
            my.alert({
              title: res.data.msg,
              buttonText: '确定',
              success: () => {
              //   const { user_id, testUrl } = getApp().globalData
              //   my.request({
              //     url: `${testUrl}/api/index/activityRecord`,
              //     data: {
              //       source: 5,
              //       user_id,
              //     },
              //     success: () => {
              //       my.navigateTo({
              //       url: '/page/rent/h5/noSesameRentMachine/noSesameRentMachine'
              //     })
              //   }
              // })
              }
            });
        
          } else if(res.data.status === '101') {
            
            my.confirm({
              title: res.data.msg,
              confirmButtonText: '咨询客服',
              cancelButtonText: '取消',
              success: (result) => {
                const { confirm } = result
                if(confirm) {
                  this.showKefu()
                }
              },
            });

          }  else { // 其它异常
            my.showToast({
              type: 'fail',
              content: res.data.msg,
              duration: 2000,
            });
          }
        },
        complete: () => {
          my.hideLoading();
        }
      });
    }

    // 当前支付宝版本是否可用交易组件 checkBeforeAddOrder API
    if (my.canIUse('checkBeforeAddOrder')) {
      my.checkBeforeAddOrder({
        success({ requireOrder, sceneId, sourceId }) {

          submitParam.scene_id = sceneId || ''
          submitParam.source_id = sourceId
          paymentOrder(submitParam)
        },
        fail({ error, errorMessage: content }) {
          my.showToast({
            type: 'none',
            content,
            duration: 3000,
          })
        },
        complete() {
          my.hideLoading();
        },
      })
    } else {
      // 不可以,则正常调用支付流程
      submitParam.scene_id = ''
      submitParam.source_id = ''
      paymentOrder(submitParam)
    }

   
  },
  onLoad(option) {
    
    //加载动画
    my.showLoading({
      content: '加载中...',
      delay: 0,
    });

    
    my.removeStorage({ //移除是否是第一次进行人脸识别
      key: 'firstFaceauth',
    });
    var orderNo = option.order_id; //后台生成的临时订单id

    let { exclusive_price, 
          is_show_exclusive, 
          safe_id, 
          safe_price, 
          isSelectBrokenScreen, 
          isSelect,
          user_voucher_id,
          zm_user_id,
          link_source,
          platform,
          s_m_user_voucher_id,
          s_m_exclusive_price,
          s_m_safe_id,
          s_m_attr_id,
          s_m_safe_info,
          s_m_is_select_safe,
          s_m_is_first_month_one_yuan
        } = option

    
    if(is_show_exclusive === 'false') {
      is_show_exclusive = ''
    }

    // 检测是否从其它来源进来的,比如分享渠道
    if(platform) {
      app.globalData.platform = platform
    }

    isSelect = !!parseInt(isSelect)
    isSelectBrokenScreen = !!parseInt(isSelectBrokenScreen)
    if(isSelect || isSelectBrokenScreen) {
      this.setData({
        temporarilyBrokenScreen: true
      })
    }


    this.setData({
      attr_id: option.attr_id,
      imgUrl: app.globalData.imgUrl,
      orderNo: orderNo,
      phone: app.globalData.userPhone || '',
      exclusive_price,
      is_show_exclusive,
      safe_id,
      safe_price,
      isSelectBrokenScreen, // switch开关
      isHideBrokenScreen: isSelect, // 隐藏碎屏险卡片
      user_voucher_id: user_voucher_id && parseInt(user_voucher_id) // 有才做数字转换
    })


    if (option.orderid) {
      this.setData({
        order_id: option.orderid
      })
      this.toBuyOut(option.orderid)
    } else {
      // vm.getOrderDetail();
    }

    
    if(link_source) {
      const info = {
        link_source,
        s_m_user_voucher_id: s_m_user_voucher_id ? parseInt(s_m_user_voucher_id) : '',
        s_m_exclusive_price,
        s_m_safe_id: parseInt(s_m_safe_id),
        s_m_attr_id: parseInt(s_m_attr_id),
        s_m_safe_info: JSON.parse(s_m_safe_info),
        s_m_is_select_safe: parseInt(s_m_is_select_safe),
        s_m_is_first_month_one_yuan: parseInt(s_m_is_first_month_one_yuan)
      }
      
      this.getUserLowerOrderState(zm_user_id, info)
    } else {
      this.refusalQuantityUser()
    }
    
  },
  onShow() { //页面显示

    this.getOrderDetail();

    this.setData({
      isUploadUserInfo: my.getStorageSync({
        key: 'has_user_info_photo'
      }).data || false
    })
    my.getStorage({ //页面返回处理
      key: 'isbackreal',
      success:  (res) => {
        if (res.data != null) {
          this.getOrderDetail()
          my.removeStorage({
            key: 'isbackreal',
          });
        }
      }
    });
    if (app.globalData.addressId) {
      this.getAddressData();
    }
  },

  onReady() {
    this.getContactsInfo()
  },

  onShareAppMessage() {
    const app = getApp()
    const { globalData: { title } } = app
    let {
      attr_id:id,
      isSelectBrokenScreen,
      orderNo: order_id,
      exclusive_price: e_price,
      is_show_exclusive: is_exclusive,
      safe_id,
      safe_price,
      isHideBrokenScreen: isSelect,
      user_voucher_id
    } = this.data
    
    isSelect =  isSelect ? 1 : 0
    isSelectBrokenScreen = isSelectBrokenScreen ? 1 : 0
    return {
      title,
      desc: `${title} 信用免押 更多爆款超低价格`,
      path: `/page/rent/confirm-order/confirm-order?order_id=${order_id}&attr_id=${id}&exclusive_price=${e_price}&is_show_exclusive=${is_exclusive}&safe_id=${safe_id}&safe_price=${safe_price}&isSelectBrokenScreen=${isSelectBrokenScreen}&isSelect=${isSelect}&user_voucher_id=${user_voucher_id}&platform=miniProgram`,
    }
  },

  events: {
    onBack() {
      let pages = getCurrentPages(); // 当前页面
      let beforePage = pages[pages.length - 2]; // 上一页

      const { one_yuan } = this.data.orderDetail
      if(one_yuan) {
        beforePage.setData({
          isShowFirstMonthProup: true
        })
        return
      }

      const {
        couponMaxPrice,couponStrength,couponTime
      } = this.data
      const isCoupon = 
      [ couponMaxPrice,couponStrength,couponTime].includes('')
      // 若优惠券为空
      if(isCoupon) {
        return
      }
      
      beforePage.dislogCountdown() // 开启倒计时
      beforePage.setData({
        showRetention:true, // 开启弹窗
        couponMaxPrice,
        couponStrength,
        couponTime
      })
    }
  },

  getUserLowerOrderState(zm_user_id, info) {

    let {
      link_source,
      s_m_user_voucher_id: user_voucher_id,
      s_m_exclusive_price: exclusive_price,
      s_m_safe_id: safe_id,
      s_m_attr_id: attr_id,
      s_m_safe_info: safe_info,
      s_m_is_select_safe: is_default_select_safe_confirm_order,
      s_m_is_first_month_one_yuan: is_first_month_one_yuan
    } = info

    if(is_first_month_one_yuan) { // 首月1元商品，把优惠券id设为空
        user_voucher_id = ''
    }

    if(safe_id && safe_info.length) { // 碎屏险id有 同时 碎屏险信息有代表用户选中了碎屏险

      this.setData({
        safe_price: '', // 碎屏险价格
        safe_id, // 碎屏险ID
        isHideBrokenScreen: true,// 是否隐藏碎屏险卡片  1隐藏，0显示
        isSelectBrokenScreen: !!is_default_select_safe_confirm_order, // 碎屏险switch是否选中 1 选中 0 补选中
        temporarilyBrokenScreen: true // true代表碎屏险ID选中
      })
    }

    if(!safe_id && !safe_info.length) { // 碎屏险id无，同时没有碎屏险信息，代表是手表耳机之类的没有碎屏险
      this.setData({
        safe_price: '',
        safe_id: 0,
        isHideBrokenScreen: true,
        isSelectBrokenScreen: false,
        temporarilyBrokenScreen: false
      })
    }

    if(!safe_id && safe_info.length) { // 碎屏险id无，但是碎屏险信息有，给用户默认打开碎屏险
      const {
        safe_price,
        id: safeId
      } = safe_info[0]
      this.setData({
        safe_price,
        safe_id: safeId,
        isHideBrokenScreen: false,
        isSelectBrokenScreen: !!is_default_select_safe_confirm_order,
        temporarilyBrokenScreen: true
      })
    }

    this.setData({
      exclusive_price, // 专享价
      attr_id, // 优惠券接口所需ID
      is_show_exclusive: !!exclusive_price, // 是否隐藏专享价
      zm_user_id, // 支付宝用户ID
      user_voucher_id, // 当前优惠券
      link_source
    })
    app.getAuth_base()
    this.getOrderDetail()

  },

  // 获取联系人信息
  async getContactsInfo() {
    const app = getApp()
    const { zm_user_id } = this.data
    const { data } = await getAddressList({
      zm_user_id: app.globalData.user_id || zm_user_id
    });
    if(data.length === 0) { // 地址为空返回
      return
    }
    let { 
      receiver_name: fullname, 
      receiver_phone: mobilePhone, 
      address,
      area,
      provinces,
      city,
      district
    } = data[0]

  
    this.setData({
      address_info: {
        fullname, 
        mobilePhone, 
        address,
        area,
        provinces,
        city,
        district
      },
    });
  },

  getOrderDetail() { //获取临时订单详情
    let app = getApp();
    let vm = this;

    let { safe_id, temporarilyBrokenScreen, zm_user_id } = vm.data
    console.log(app.globalData.user_id, 'safe_id');
    //获取临时订单信息
    my.request({
      url: app.globalData.testUrl + '/Api/order/ConfirmOrder',
      method: 'POST',
      data: {
        order_id: vm.data.orderNo,
        zm_user_id: app.globalData.user_id || zm_user_id,
        user_voucher_id: vm.data.user_voucher_id,
        exclusive_price: vm.data.exclusive_price,
        safe_id: temporarilyBrokenScreen ? parseInt(safe_id) : 0
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.status == '1001') {
          let _setData = {
            is_auth: res.data.data.is_auth,
            orderDetail: res.data.data,
          }
          const { sesame_exclusive_discount_amount = '' } = res.data.data
          vm.setData({
            is_skip_face_auth: res.data.data.is_skip_face_auth,
            sesame_exclusive_discount_amount,
            is_exclusive_discounts: Boolean(sesame_exclusive_discount_amount)
          })

          // if (res.data.data.user_email && res.data.data.user_email != "") {
          //   _setData.emailstr = res.data.data.user_email;
          // }
          // 赋值地址
          // if (vm.data.address_info == null) {

          //   if (res.data.data.user_address != "" && res.data.data.receiver_name && res.data.data.receiver_phone) {

          //     _setData.address_info = {
          //       fullname: res.data.data.receiver_name,
          //       mobilePhone: res.data.data.receiver_phone,
          //       address: res.data.data.user_address
          //     }
          //   }
          // }

          let {
            order_monthly_rent,
            first_month_rent,
            order_actual_month_rent
           } = res.data.data;
  
          const convertNumbers = () => {
           
 
            order_monthly_rent = order_monthly_rent && Number(order_monthly_rent)
            first_month_rent = first_month_rent && Number(first_month_rent)
            order_actual_month_rent = order_actual_month_rent && Number(order_actual_month_rent)
            
            if(order_monthly_rent === first_month_rent) { // 价格相同隐藏原首期租金
              vm.setData({
                isHideOriginFirstInstallmentRent: false
              })
            }
        

            if(order_monthly_rent === order_actual_month_rent) { // 价格相同隐藏剩余总租金
              console.log('进来了');
              vm.setData({
                isHideRemainingTotalRent: false
              })
            }
          }
  
          convertNumbers()


          vm.setData(_setData);
          vm.requestVoucherLists() //优惠劵
          my.hideLoading();
          vm.compute_price();

        }
      },
      fail: (res) => {
        console.log('失败', res.data);
      },
      complete: () => {
        my.hideLoading();
      }
    });
  },
  async getAddressData() {
    let { data: {
      receiver_name, 
      receiver_phone, 
      address, 
      area,
      provinces,
      city,
      district
    } } = await findAddress({
      id: app.globalData.addressId
    });

    this.setData({
      address_info: {
        fullname: receiver_name,
        mobilePhone: receiver_phone,
        address,
        area,
        provinces,
        city,
        district
      }
    })
  },
  toGoodsDetail(e) {
    // const { goods_id } = this.data.orderDetail
    // my.navigateTo({
    //   url: "../goodsdetail/goodsdetail?id=" + goods_id
    // })
  },
  // engineOnclick(e) {//邮箱提示点击

  //   this.setData({
  //     emailstr: this.data.emailstr + e.currentTarget.dataset.suffix,
  //     showEngine: false
  //   })
  // },
  bindTextAreaBlur(e) { //备注信息

    this.setData({
      remark: e.detail.value
    })
  },
  rule_explain(e) { //点击使用规则说明
    let _tap_index = e.currentTarget.dataset.tap_index;
    if (this.data.tap_role_index == _tap_index) {
      this.setData({
        tap_role_index: -1
      })
    } else {
      this.setData({
        tap_role_index: _tap_index
      })
    }
  },

  // 预授权支付
  preAuthorization() {
    const { _orderStr: orderStr  } = this.data
    const { order_id } = this.data.orderDetail
    my.tradePay({
      orderStr,
      success: (res1) => {
        let _code = res1.resultCode;
        if (_code === "9000") { //成功
          let _auth_no = res1.result && JSON.parse(res1.result).alipay_fund_auth_order_app_freeze_response.auth_no;
          let _credit_amount = res1.result && JSON.parse(res1.result).alipay_fund_auth_order_app_freeze_response.credit_amount;
          my.redirectTo({
            url: `../order-result/order-result?order_id=${order_id}&auth_no=${_auth_no}&status=SUCCESS&credit_amount=${_credit_amount}`
          })

        } else if (_code == "6001") { //用户自主取消
          my.hideLoading(); //加载结束
          my.redirectTo({
            url: "../../mine/myorders/myorders?id=99",
          });
        } else { //失败
          my.hideLoading(); //加载结束
          my.redirectTo({
            url: `../order-result/order-result?order_id=${order_id}&status=FAIL`
          });
        }
      },
      fail: () => {
        my.hideLoading(); //加载结束
        my.redirectTo({
          url: `../order-result/order-result?order_id=${order_id}&status=FAIL`
        });
      }
    });
  },

  // 人脸识别认证
  authentication() { 
    let app = getApp();
    const { testUrl, user_id: zm_user_id } = app.globalData
    const { submitParam: { order_id } } = this.data
    //加载动画
    my.showLoading({
      content: '加载中...',
      delay: 0,
    });
    my.request({
      url: `${testUrl}/api/user/userFaceAuth`,
      method: 'POST',
      data: {
        order_id,
        zm_user_id
      },
      dataType: 'json',
      success: (res) => {
        const { code } = res.data
        if (code === 1) {
          const { certify_url, certify_id } = res.data.data
          my.startAPVerify({
            url: certify_url,
            certifyId: certify_id,
            success: res => {
              if (res.resultStatus === "9000") {
                my.request({
                  url: `${testUrl}/api/user/userFaceAuthSuccess`,
                  method: 'POST',
                  data: {
                    order_id
                  },
                  dataType: 'json',
                  success: () => {
                    this.preAuthorization()
                  },
                  fail: () => { // 成功和失败都拉起预授权
                    // 拉起预授权
                    this.preAuthorization()
                  }
                })
                
              } else {
                my.showToast({
                  content: res.resultStatus === "6001" ? "请先完成人脸识别" : '人脸识别失败！',
                })
                my.redirectTo({
                  url: `../order-result/order-result?order_id=${order_id}&status=FAIL`,
                });
              }
            },
            fail: () => {
              my.redirectTo({
                url: `../order-result/order-result?order_id=${order_id}&status=FAIL`
              });
            },
            complete: () => {
              my.hideLoading(); //加载结束
            }
          })
        } else{
          // 跳到下单失败
          my.redirectTo({
            url: `../order-result/order-result?order_id=${order_id}&status=FAIL`
          });
        }
      },
      fail: () => {
        my.redirectTo({
          url: `../order-result/order-result?order_id=${order_id}&status=FAIL`
        })
      },
      complete: () => {
        my.hideLoading(); //加载结束
      }
    })

  },
  startAPVerify(options, callback) { //调起人脸识别
    my.call('startBizService', {
      name: 'open-certify',
      param: JSON.stringify(options),
    }, callback);
  },

  compute_price() { //计算金额
    let vm = this;
    let _order_goods_insurance = vm.data.orderDetail.order_goods_insurance == null ? 0 : vm.data.orderDetail.order_goods_insurance; //意外保障

    let _order_gross_rent = parseFloat(vm.data.orderDetail.order_gross_rent) - parseFloat(_order_goods_insurance); //除去意外保障租金

    let _order_tenancy_term = vm.data.orderDetail.order_day_rent; //租用天数

    let _day_price = parseFloat(_order_gross_rent) / parseFloat(_order_tenancy_term); //日租金

    let _voucher = vm.data.usingVoucher; //当前选择的优惠券 


    //首期总租金
    let _total_price = (parseFloat(30) * parseFloat(_day_price));
    if (_order_tenancy_term < 30) {
      _total_price = parseFloat(_day_price) * parseFloat(_order_tenancy_term);
    }

    let _price = 0; //优惠后价格
    if (vm.data.selectvoucherid == 0) {
      _voucher = {};
      _price = _total_price;
    } else {
      if (_voucher.cou_type == 1) { //折扣券
        _price = parseFloat(_total_price) * parseFloat(_voucher.cou_sum_price);
      } else if (_voucher.cou_type == 3) { //满减 
        _price = parseFloat(_total_price) - parseFloat(_voucher.cou_price);
      } else if (_voucher.cou_type == 6) { //0元租7天
        _price = parseFloat(_total_price) - parseFloat(_day_price) * parseFloat(_voucher.cou_price);
      } else if (_voucher.cou_type == 11) { //首月1元
        _price = 1;
      } else {
        _price = parseFloat(_day_price) * 30;
      }
    }
    if (vm.data.orderDetail.one_yuan) {
      vm.setData({
        down_payments: (parseFloat(vm.data.orderDetail.first_month_actual_amount) + parseFloat(_order_goods_insurance)).toFixed(2)
      })
    } else {
      vm.setData({
        down_payment: (parseFloat(vm.data.orderDetail.after_voucher_month_rent || vm.data.orderDetail.order_monthly_rent) + parseFloat(_order_goods_insurance)).toFixed(2)
      })
    }

  },
  toBuyOut(order_id) {
    let vm = this;
    my.request({
      url: app.globalData.testUrl + '/Api/order/getBuyoutInfo',
      method: 'POST',
      data: {
        order_id: order_id
      },
      dataType: 'json',
      success: (res) => {
        if (res.data.status == 1001) {
          let data = res.data.data
          data.need_pay = parseFloat(data.need_pay).toFixed(2)
          console.log(data, '买断信息');
          this.setData({
            buyOutMsg: data
          })
        }
        my.hideLoading()
      },
      fail: () => {
        this.setData({
          buyOutMsg: {
            need_pay: 0.00
          }
        })
        my.hideLoading()
      }
    })
  },
  cashSub() {
    let vm = this;
    my.request({
      url: app.globalData.testUrl + '/Api/order/callBuyoutBar',
      method: 'POST',
      data: {
        order_id: vm.data.order_id,
        zm_user_id: app.globalData.user_id
      },
      dataType: 'json',
      success: (res) => {
        if (res.data.status == 1001) {
          my.tradePay({
            tradeNO: res.data.data,
            success: res => {
              if (res.resultCode === "9000") {
                my.navigateTo({
                  url: `/page/mine/myorders/myorders`
                })
              }
            },
            fail: res => {
              my.alert({
                content: "支付失败，请重试"
              })
            }
          })
        }
      },
      fail: res => {
        my.alert({
          content: "请求失败，请重试"
        })
      }
    })
  },
  gotoUserInfo() {
    my.navigateTo({
      url: `/page/mine/upload_codeImg/upload_codeImg?codeName=${this.data.orderDetail.user_name}&is_financial=${this.data.is_financial}&is_warrant=${this.data.is_warrant}&t=0`,
    })
  },
});